#!/usr/bin/python

import sys
import os
import os.path
import shutil
import codecs
import json
import jrdUtils
from xml.etree import ElementTree
from pyXls import *

#----------------------------------------------------
# Global Variables
#----------------------------------------------------

_l10nPath = 'gaia/jrd-l10n/'
_xlsPath = 'ffos_wimdata_ng/wlanguage/src/'
# All languages comparison table, to translate the language name of XLS  into shortname.
_allLangsDict = jrdUtils.getLangsDictFromLangsList(jrdUtils.getLangsListFromJson())

#store column informations
_langList = []
#store id informations
_idDict = {}
# Language starting position of excel file
_langStartPosition = 7

#----------------------------------------------------
# Functions
#----------------------------------------------------

def initIdDictAndLangList(langs, tableDict):
    #initialize idDict and langList
    for cell in tableDict:
        #generate message id list
        if cell[1] == 0 and cell[0]!=0 :
            strId = tableDict[cell]
            _idDict[cell[0]-1] = strId

        #generate language list
        if cell[0] == 0 and cell[1] >= _langStartPosition:
            if _allLangsDict.has_key(tableDict[cell]):
                key = _allLangsDict[tableDict[cell]]
                print '    Add language: %s' % key
            else:
                assert False, 'Not add the language: "%s" in build/languages_table_list.json!' % tableDict[cell]
            _langList.append((tableDict[cell], cell[1]))
    print 'Language List with column number in table:\n %s' % _langList

def xlsToMsgDict(tableDict):
    msgDict = {}

    for idx in _idDict:
        msgId = _idDict[idx]
        msgDict[msgId] = {}
        rowDict = msgDict[msgId]
        for lang in _langList:
            sLangName = _allLangsDict[lang[0]]
            row = idx+1
            column = lang[1]
            if tableDict.has_key(((row,column))):
                rowDict[sLangName] = tableDict[(row,column)]
        #print rowDict
    #print msgDict
    return msgDict

def msgDictToFileDict(msgDict):
    fileDict = {}

    for items in msgDict:
        i = items.rfind(':')
        msgId = items[i+1:]
        filePathStr = items[:i]
        translation = msgDict[items]

        #print filePathStr,msgId,translation

        msgTuple = (msgId, translation)

        if not fileDict.has_key(filePathStr):
            fileDict[filePathStr] = []
        fileDict[filePathStr].append(msgTuple)

    #print fileDict
    return fileDict

def fileDictToOutPutDict(fileDict):
    outPutDict = {}
    for files in fileDict:
        pathAndName = files.replace(':','/') + '.properties'
        #print pathAndName

        msgList = fileDict[files]
        for msg in msgList:
            msgid = msg[0]
            strDict = msg[1]
            for lang in strDict:
                filepath = _l10nPath + lang + '/apps/' + pathAndName
                if not outPutDict.has_key(filepath):
                    outPutDict[filepath] = ''
                msgstr =  msgid + '=' + strDict[lang] + '\n'
                outPutDict[filepath] += msgstr

    return outPutDict

def outPutDictToFiles(outPutDict):
    #print outPutDict
    for filepath in outPutDict:
        i = filepath.rfind('/')
        filedir = filepath[:i]
        msg = outPutDict[filepath]

        if not os.path.exists(filedir):
            os.makedirs(filedir)
        os.mknod(filepath)

        msgFile = codecs.open(filepath,'wb',"utf_8")
        msgFile.write(msg)
        msgFile.close()

def clearL10nPath():
    for lang in _allLangsDict:
        path = _l10nPath + _allLangsDict[lang]
        if os.path.exists(path):
            shutil.rmtree(path)

def genJrdl10nProperties(langs):
    if (len(sys.argv) > 1):
        xlsFile = sys.argv[1]
    elif os.path.isfile(_xlsPath+"strings.xls"):
        xlsFile = "strings.xls"
    else:
        print "Xls File not found!"
        return

    clearL10nPath()

    sheets = parse_xls(_xlsPath + xlsFile)
    tableDict = sheets[0][1]
    initIdDictAndLangList(langs, tableDict)

    msgDict = xlsToMsgDict(tableDict)
    fileDict = msgDictToFileDict(msgDict)
    outPutDict = fileDictToOutPutDict(fileDict)

    outPutDictToFiles(outPutDict)
    print 'Generate properties files successed!!'
# gen languages.json for product_language.mk
def genLanguageJsonFile(text,dest):
    allLanguagesPath = 'gaia/locales/languages_all.json'

    fAllLangs = codecs.open(allLanguagesPath, 'rb', 'utf_8')
    allLangsStr = fAllLangs.read()
    fAllLangs.close()
    allLangsDict = json.loads(allLangsStr)

    jsonStr = '{'

    langList = (text.strip('"')).split('\\n')

    for lang in langList:
        if allLangsDict.has_key(lang):
            jsonStr += '\n  "%s": "%s",' % (lang, allLangsDict[lang])
        else:
            assert False,  'Not have the language: "%s" in gaia/locales/languages_all.json!' % lang

    lastCommaIdx = jsonStr.rfind(',')
    if lastCommaIdx > -1:
      jsonStr = jsonStr[:lastCommaIdx]
    jsonStr += '\n}'

    fOut = codecs.open(dest, 'wb', 'utf_8')
    fOut.write(jsonStr)
    fOut.close()

    fLangs = codecs.open(dest, 'rb', 'utf_8')
    langsStr = fLangs.read()
    fLangs.close()
    langs = json.loads(langsStr)

    print 'Generate %s successed!' % dest
    return langs

# gen product_language.mk from plf
def genLanguageMKFileFromPlf():
    scrLangPath = 'ffos_wimdata_ng/wprocedures/isdm_Languages.plf'
    destJSONPath = 'gaia/locales/languages_perso.json'

    destMKPath = 'gaia/build/product_language.mk'
    text = ''
    multilocalStr = ''

    if os.path.exists(scrLangPath):
        fIn = codecs.open(scrLangPath, 'rb', 'utf_8')
        text = fIn.read()
        fIn.close()
        root = ElementTree.fromstring(text)
        varNodes = root.getiterator('VAR')
        for node in varNodes:
            sdmidTag = node.find('SIMPLE_VAR/SDMID')
            valueTag = node.find('SIMPLE_VAR/VALUE')
            if sdmidTag.text == 'PRODUCT_LOCALES':
                langsStr = valueTag.text
                multilocalStr = (langsStr.replace('\\n',' ')).strip('"')
                print "Customized languages are: %s" % multilocalStr
                langs = genLanguageJsonFile(langsStr,destJSONPath)

    #For serbian, in gaia named 'sr-Latn', and in gecko named 'sr'.
    # if multilocalStr.find('sr-Cyrl') > -1:
    #     multilocalStr = multilocalStr.replace('sr-Cyrl','sr')
    if multilocalStr.find('sr-Latn') > -1:
        multilocalStr = multilocalStr.replace('sr-Latn','sr')
    #For Latn-ESP, in gaia named 'es', and in gecko named 'es-ES'.
    if multilocalStr.find('es') > -1:
        multilocalStr = multilocalStr.replace('es','es-ES')

    text = 'PERSO_LOCALES_FILE=locales/languages_perso.json'
    text += '\nPERSO_MOZ_CHROME_MULTILOCALE=' + multilocalStr
    text += '\nexport PERSO_LOCALES_FILE'
    text += '\nexport PERSO_MOZ_CHROME_MULTILOCALE'

    fOut = codecs.open(destMKPath, 'wb', 'utf_8')
    fOut.write(text)
    fOut.close()
    print 'Generate %s successed!' % destMKPath

    return langs

    #if moz_chrome_multilocalStr != '':


#----------------------------------------------------
# main
#----------------------------------------------------

def main():
    langs = genLanguageMKFileFromPlf()
    #out put strings.xml to jrd-l10n directory
    genJrdl10nProperties(langs)



if __name__ == '__main__':
    main()
